package org.jeecg.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.domain.User;
import org.jeecg.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author scott
 * @Date 2019/9/23 14:12
 * @Description: 编程校验token有效性
 */
@Slf4j
public class TokenUtils {

    /**
     * 获取 request 里传递的 token
     *
     * @param request
     * @return
     */
    public static String getTokenByRequest(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getHeader("X-Access-Token");
        }
        return token;
    }

    /**
     * 验证Token
     */
    public static boolean verifyToken(HttpServletRequest request, UserMapper commonApi) throws Exception {
        log.debug(" -- url --" + request.getRequestURL());
        String token = getTokenByRequest(request);
        return TokenUtils.verifyToken(token, commonApi);
    }

    /**
     * 验证Token
     */
    public static boolean verifyToken(String token, UserMapper commonApi) throws Exception{
        if (StringUtils.isBlank(token)) {
            throw new Exception("token不能为空!");
        }

        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(token);
        if (username == null) {
            throw new Exception("token非法无效!");
        }

        // 查询用户信息
        User user = TokenUtils.getLoginUser(username, commonApi);
        //LoginUser user = commonApi.getUserByName(username);
        if (user == null) {
            throw new Exception("用户不存在!");
        }
//        // 校验token是否超时失效 & 或者账号密码是否错误
//        if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
//            throw new Exception(CommonConstant.TOKEN_IS_INVALID_MSG);
//        }
        return true;
    }

    /**
     * 获取登录用户
     *
     * @param userMapper
     * @param username
     * @return
     */
    public static User getLoginUser(String username,UserMapper userMapper) {
        User loginUser = null;
        // 查询用户信息
        loginUser = userMapper.getUser(username);
        return loginUser;
    }
}
